<template>
  <div class='rank'>
    <div class="rank-type">
      <div class="type-title">考生类型</div>
      <div @click="setRadio('examType',item,examTypes)" v-for="(item, index) in examTypes" :key="index" class="radio-list">
        <div class="radio-item">
          <i v-if="item.select" class="weui-icon-checked i-checked"></i>
        </div>
        <span>{{item.name}}</span>
      </div>
    </div>

    <div class="rank-line">成绩位次</div>

    <div class="rank-score">

      <popup-picker class="item-picker" v-if="info.examType == 2" title="请选择科类代码" :data="artTypeList" v-model="artVal" @on-change="onArtChange" placeholder="选择专业科目"></popup-picker>

      <div v-if="info.examType==2" class="score-item">
        <div class="item-title"><span>专业省统考成绩</span></div>
        <div style="flex:1"><input v-model="info.artScore" class="input" @blur="checkSubValue('')" maxlength="3" placeholder="请输入专业分数" type="tel"></div>
      </div>

      <div v-for="(item, index) in subject" :key="index" class="score-item">
        <div class="item-title-core"><span>{{item.name}}</span></div>
        <input v-if="!item.isShowCheck"  @blur="checkSubValue(item)" v-model="item.score" class="input bc-t" maxlength="3" :placeholder="'请输入'+item.name+'分数'" type="tel">
        <input v-if="item.isShowCheck&&item.select" @blur="checkSubValue(item)" v-model="item.score" class="input bc-t" maxlength="3" :placeholder="'请输入'+item.name+'分数'" type="tel">
        <input v-if="item.isShowCheck&&!item.select" :disabled="true" @blur="checkSubValue(item)" v-model="item.score" class="input bc-t" maxlength="3" :placeholder="'请输入'+item.name+'分数'" type="tel">
        <div @click="subSelect(item)" v-if="item.isShowCheck" class="item-check">
          <div class="check-box"><i v-if="item.select" class="weui-icon-checked i-checked"></i></div>
        </div>
      </div>

      <popup-picker class="pluspicker" title="加分项" :data="plusScoreArr" v-model="plusScoreVal" @on-change="onValuesChange" placeholder="选择加分项"></popup-picker>
    </div>

    <div class="rank-line">成绩位次</div>

    <div class="rank-about">
      <div class="about-item">
        <div class="about-titles"><span>2019成绩</span></div>
        <div class="about-cores">{{info.score}}</div>
      </div>

      <div class="about-item">
        <!-- 模拟位次 -->
        <div class="about-titles"><span>模拟位次</span></div>
        <!-- <div class="about-cores">{{info.rank}}</div> -->
        <input placeholder="请输入模拟位次" @blur="rankChang" class="input bc-t" v-model="info.rank" maxlength="10" type="tel">
      </div>

      <div class="about-item">
        <div class="about-titles"><span>2018/2017成绩</span></div>
        <div class="about-cores">{{info.advice}}</div>
      </div>
    </div>

    <div v-if="userinfo.changeCount==0" class="buy-tip">
      <div>
        <span v-if="userinfo.changeCount==0" style="color:red;">您的成绩（位次）修改次数已用完！</span>
        <span v-if="userinfo.changeCount > 0 " style="color:red;">您是体验用户，还有{{changeCount}}次修改成绩的机会！</span>
        <span v-if="userinfo.type == 102" @click="$router.push({name: 'goodsPay', query: {t: 'all'}})" class="buy-to">去购买</span>
      </div>
    </div>

    <div class="btn-next-group">
      <a :class="[userinfo.changeCount==0?'btn-bakc':'btn-next']" href="javascript:;" @click="saveRank()">保 存</a>
    </div>

    <div style="height:30px;background-color: #f2f2f2;"></div>

  </div>
</template>

<script>
import Api from '@/api/index.js';
import Utils from '@/common/utils.js'
import { PopupPicker, Group } from 'vux';
export default {
  components: {
    Group,
    PopupPicker,
  },
  data() {
    return {
      changeCount: 0,
      userinfo: {},
      popupArtType: false,
      slots: [],
      slotType: '',
      artVal: ['美术类'],
      plusScoreVal: ['0分'],
      autoRank: 0,
      info: {
        scores: [],
        plusScore: 0,
        examType: 1,
        rank: '',
        artSubject: '美术类',
        artScore: '',
        score: '',
        advice: ''
      },
      scoreRank: {
        type: '普通类',
        rank: 0,
        score: 0
      },
      artTypeList: [['美术类', '音乐类', '舞蹈类', '影视类', '时装类', '播音类', '编导类', '摄制类', '体育类']],
      plusScoreArr: [['0分', '3分', '5分', '20分']],
      examTypes: [
        { value: '1', name: '普通考生', select: true },
        { value: '2', name: '艺体考生', select: false }
      ],
      subject: [
        { name: '语文', score: '', isShowCheck: false, select: false, isDis: false, max: 150, old: 0 },
        { name: '数学', score: '', isShowCheck: false, select: false, isDis: false, max: 150, old: 0 },
        { name: '外语', score: '', isShowCheck: false, select: false, isDis: false, max: 150, old: 0 },
        { name: '化学', score: '', isShowCheck: true, select: false, isDis: false, max: 100, old: 0 },
        { name: '历史', score: '', isShowCheck: true, select: false, isDis: false, max: 100, old: 0 },
        { name: '地理', score: '', isShowCheck: true, select: false, isDis: false, max: 100, old: 0 },
        { name: '政治', score: '', isShowCheck: true, select: false, isDis: false, max: 100, old: 0 },
        { name: '技术', score: '', isShowCheck: true, select: false, isDis: false, max: 100, old: 0 },
        { name: '物理', score: '', isShowCheck: true, select: false, isDis: false, max: 100, old: 0 },
        { name: '生物', score: '', isShowCheck: true, select: false, isDis: false, max: 100, old: 0 }
      ]
    }
  },
  methods: {
    selectType(type) {
      this.popupArtType = true;
      this.slotType = type;
      if (type == 'subject') {
        this.slots = this.artTypeList;
        this.slots[0].defaultIndex = this.slots[0].values.findIndex(v => { return v == this.info.artSubject });
      } else if (type == 'score') {
        this.slots = this.plusScoreArr;
      }
      this.autoCount();
    },
    rankChang() {
      this.info.rank = parseInt(this.info.rank || 0);
      this.autoCount();
    },
    setRadio(model, item, obj) {
      obj.forEach(element => {
        element.select = false
      });
      item.select = true;
      this.info[model] = item.value;
      this.autoCount();
    },
    subSelect(item) {
      let isFirst = !this.userinfo.score;
      let sect = this.subject.filter(v => { return v.select }).length;

      //不是首次与非vip用户，不能在次勾选
      if (!isFirst && this.userinfo.type == 102) {
        return;
      }

      if (this.userinfo.subjectChangeCount <= 0) {
        return;
      }

      sect += item.select ? 0 : 1;
      if (sect > 3) {
        this.$vux.toast.show({ text: '最多选择3门科目，如需更改，请先取消勾选其他科目', type: 'text', width: '80%' })
        return;
      }

      if (item.select) {
        item.select = false;
        item.score = '';
        // item.isDis = true;
      } else {
        item.select = true;
        item.isDis = false;
        if (item.score == '') {
          item.score = '';
        }
      }

    },
    checkSubValue(item) {
      if (item) {
        //当大于自身最大值等于最大值
        if (parseInt(item.score) && parseInt(item.score) > item.max) {
          item.score = item.max;
        }
        //当小于0时，等于0
        if ((parseInt(item.score) && parseInt(item.score) < 0)) {
          item.score = 0;
        }
        //当为非数字时清空
        if (item.score != '' && !parseInt(item.score == 0 ? 1 : item.score)) {
          item.score = '';
        }
        let sect = this.subject.filter(v => { return v.select }).length;
        //新用户，或VIP用户可以重新修改
        if (!this.userinfo.score || this.userinfo.type == 103) {
          //当分数不为空选中项少于3，与非必填项时
          if (parseInt(item.score) && parseInt(item.score) > 0 && sect < 3 && item.isShowCheck) {
            item.select = true;
          }
          if (sect >= 2 && !item.select && item.score != '' && item.isShowCheck) {
            this.$vux.toast.show({ text: '最多选择3门科目，如需更改，请先取消勾选其他科目', type: 'text', width: '80%' })
            item.score = '';
            return;
          }
        }
        if (item.score) {
          item.score = parseInt(item.score);
        }
      } else {
        //当大于自身最大值等于最大值
        if (parseInt(this.info.artScore) && parseInt(this.info.artScore) > 100) {
          this.info.artScore = 100;
        }
        //当小于0时，等于0
        if ((parseInt(this.info.artScore) && parseInt(this.info.artScore) < 0)) {
          this.info.artScore = 0;
        }
        //当为非数字时清空
        if (this.info.artScore != '' && !parseInt(this.info.artScore == 0 ? 1 : this.info.artScore)) {
          this.info.artScore = '';
        }
      }
      if (item.isShowCheck && item.score && !this.ruleScore(parseInt(item.score), item.max)) {
        this.$vux.toast.show({ text: item.name + '选考成绩输入错误请重新输入', type: 'text', width: '80%' })
      }
      this.autoCount();
    },
    ruleScore(v, max) {
      let min = 40;
      let curr = [];
      for (let i = 40; i <= max;) {
        curr.push(i);
        i += 3;
      }
      return curr.find(value => { return value == v })
    },
    onValuesChange(val) {
      this.plusScoreVal = val;
      this.info.plusScore = val[0] && val[0].replace('分', '');
      this.autoCount();
    },
    onArtChange(val) {
      this.artVal = val;
      this.info.artSubject = val.toString();
      this.autoCount();
    },
    autoCount() {
      //总分
      let allScore = this.subject.reduce((count, value) => { return count += parseInt(value.score) || 0 }, 0);

      if (this.info.examType == 2) {
        switch (this.info.artSubject) {
          case '体育类':
          case '美术类':
          case '音乐类':
            allScore = allScore * 0.5 + (parseInt(this.info.artScore) || 0) * 7.5 * 0.5
            break
          case '舞蹈类':
          case '影视类':
          case '时装类':
            allScore = allScore * 0.4 + (parseInt(this.info.artScore) || 0) * 7.5 * 0.6
            break
          case '播音类':
            allScore = allScore * 0.8 + (parseInt(this.info.artScore) || 0) * 7.5 * 0.2
            break
          case '编导类':
          case '摄制类':
          default:
            allScore = allScore * 1
            break
        }
      }
      allScore += parseInt(this.info.plusScore) || 0;
      allScore = parseInt(allScore.toFixed(2)) * 100 / 100;
      this.info.score = allScore;

      this.scoreRank.type = (this.info.examTypes == 2 ? this.info.artSubject : '普通类') || '普通类';
      this.scoreRank.rank = this.autoRank;
      // this.scoreRank.rank = this.info.rank;
      this.scoreRank.score = allScore;

      let qData = {
        type: this.info.examType == 2 ? this.info.artSubject : '普通类',
        score: this.info.score
      }
      if (allScore === 0) {
        this.autoRank = 0
        // this.info.rank = 0
      } else {
        Api.getRankAdvice(qData).then(res => {
          this.info.rank = res.message;
          this.autoRank = res.message;
          this.setScore()
        })
      }
    },
    setScore() {
      let qData = {
        type: this.info.examType == 2 ? this.info.artSubject : '普通类',
        rank: this.info.rank ? this.info.rank : this.autoRank
        // rank: this.info.rank
      }
      Api.getScoreAdvice(qData).then(dal => {
        if (dal.code == 20000) {
          if (dal.message) {
            let score = dal.message.split(',');
            this.info.advice = `${score[1] == 'null' ? '-' : score[1]} / ${score[0] == 'null' ? '-' : score[0]}`;
          }
        }
      })
    },
    saveRank() {
      // 没有修改次数不操作
      if (this.userinfo.changeCount == 0) {
        return false
      }

      if (parseInt(this.info.rank || 0) < 1) {
        this.$vux.toast.show({ text: '请输入模拟位次', type: 'text', width: '80%' });
        return;
      }

      this.info.scores = this.subject.map(v => { return v.score || 0 }).toString();

      let errorScore = null;
      errorScore = this.subject.find(v => {
        return !v.isShowCheck && !v.score;
      });

      if (errorScore) {
        this.$vux.toast.show({ text: '请输入' + errorScore.name + '成绩', type: 'text', width: '80%' });
        return;
      }

      if (this.subject.filter(v => { return v.select }).length < 3) {
        this.$vux.toast.show({ text: '最少选中三门选考成绩', type: 'text', width: '80%' });
        return;
      }

      errorScore = null;
      errorScore = this.subject.find(v => {
        return v.isShowCheck && v.select && !this.ruleScore(v.score, v.max);
      });
      if (errorScore) {
        this.$vux.toast.show({ text: errorScore.name + '选考成绩输入错误请重新输入', type: 'text', width: '80%' });
        return;
      }

      if (this.info.score <= 6) {
        this.$vux.toast.show({ text: '请正确填写您的专业分数', type: 'text', width: '80%' })
        return;
      }

      if (this.info.artScore <= 0 && this.info.examType == 2) {
        this.$vux.toast.show({ text: '请正确填写您的专业分数', type: 'text', width: '80%' })
        return;
      }
      // 尊敬的用户您好！为了保障您志愿查询的准确性和双方权益，自2019年6月23日起修改模拟成绩与位次号及选考科目有且只能修改一次，请仔细检查您输入各科成绩与位次号及选考是否与您模拟确定成绩信息完全对应。确定后提交，提交后成绩与位次号及选考将不能再次修改。敬请您认真核对，谢谢！
      this.$vux.confirm.show({
        title: '温馨提示',
        content: '确定要保存吗？',
        onCancel: null,
        onConfirm: () => {
          this.$vux.loading.show({ text: 'Loading' });
          setTimeout(() => {
            Api.setScoreRank(this.info).then(res => {
              this.$vux.loading.hide()
              if (res.code == 20000) {
                Utils.local('userData', res.data)
                // if (this.userinfo.type == 102) {
                if (this.userinfo.changeCount > 0 && this.userinfo.subjectChangeCount > 0) {
                  this.updateSubjectAndChangeCount(0)
                } else if (this.changeCount > 0) {
                  this.updateSubjectAndChangeCount(1)
                }
                // }
                this.$vux.toast.show({ text: '保存成功', type: 'text', width: '80%' })
                setTimeout(() => {
                  if (this.$route.query.redirect) {
                    this.$router.push({ name: this.$route.query.redirect })
                  } else {
                    this.$router.push({ name: 'mineIndex' })
                  }
                }, 700);

              }
            })
          }, 1200);
        }
      })

    },
    // 修改选课次数&成绩次数
    updateSubjectAndChangeCount(typeVal) {
      // 0 同时修改  1 changeCount  2 subjectCount
      Api.updateSubjectAndChangeCount({ type: typeVal }).then(res => {
        if (res.code === 20000) {
          this.changeCount--
        }
      })
    },
  },
  created() {
    Api.getUserInfo().then(res => {
      if (res.code == 20000) {
        this.userinfo = res.data;
        this.info.scores = res.data.scores && res.data.scores.split(',') || Array(10).fill(0);
        this.info.score = res.data.score || '-';
        this.info.rank = res.data.rank || '';
        this.autoRank = res.data.rank;
        this.info.artSubject = res.data.artSubject || '美术类';
        this.info.artScore = res.data.artScore || '';
        this.info.examType = res.data.examType || 1;
        this.scoreRank.rank = res.data.rank || 0;
        this.scoreRank.type = (res.data.examType == 2 ? res.data.artSubject : '普通类') || '普通类';
        this.changeCount = res.data.changeCount;
        this.info.plusScore = res.data.plusScore || 0;

        if (res.data.examType == 2) {
          this.info.rank = res.data.artRank || 0;
          this.autoRank = res.data.artRank || 0;
        }

        this.artVal = [];
        this.artVal.push(this.info.artSubject);

        this.plusScoreVal = [];
        this.plusScoreVal.push(this.info.plusScore + '分');

        //2018/2017成绩
        if (res.data.score2017) {
          this.info.advice = res.data.score2018.concat(' / ').concat(res.data.score2017);
        } else {
          this.setScore();
        }

        //初始考生类型
        if (res.data.examType != 0) {
          this.examTypes.forEach(v => {
            if (v.value == res.data.examType) {
              v.select = true;
            } else {
              v.select = false
            }
          })
        }

        // debugger;

        //设置科目分数，与disable
        this.subject.forEach((v, index) => {
          v.score = this.info.scores[index] == 0 ? '' : this.info.scores[index];
          v.old = this.info.scores[index];
          //是否选中
          if (v.isShowCheck && v.score) {
            v.select = true
          }
          //是否可输入 
          if (this.userinfo.score) {
            //老用户
            if (!v.isShowCheck || v.score) {
              v.isDis = false //有值时可输入
            } else {
              v.isDis = true; //无值时不可输入
            }
            if (this.userinfo.type == 103) {
              v.isDis = false;//VIP用户可输入
            }
          } else {
            //新用户可输入
            v.isDis = false
          }
        })

        this.autoCount();
      }
    })
  }
}
</script>

<style lang='less'>
.rank {
  .rank-about {
    // pl25 pr25 fs-14 bc-fff
    padding: 0 25/75rem;
    .about-item {
      height: 100/75rem;
      border-bottom: 1px solid #eee;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &:last-child {
        border-bottom: 0;
      }
      .about-titles {
        display: flex;
        align-items: center;
        width: 250/75rem;
      }
      .about-cores {
        color: #eb8718;
        flex: 1;
      }
    }
  }
  .btn-next-group {
    background-color: #f2f2f2;
    margin-top: 0;
    padding-top: 50/75rem;
    padding-bottom: 60/75rem;
  }
  .buy-tip {
    padding: 30/76rem 25/75rem;
    background-color: #f2f2f2;
    .buy-to {
      background-color: #eb8718;
      padding: 3/75rem 10/75rem;
      color: #fff;
      border-radius: 5/75rem;
    }
  }
  .item-picker,
  .pluspicker {
    &:before {
      content: none !important;
    }
    position: relative;
    height: 100/75rem;
    border-bottom: 1px solid #eee;
    .weui-cell__hd {
      width: 255/75rem;
    }
    .weui-cell_access {
      padding: 0 !important;
      display: flex;
      height: 100%;
      align-items: center;
      justify-content: space-between;
      .vux-popup-picker-select {
        text-align: left !important;
        .vux-cell-value {
          color: #eb8718 !important;
        }
      }
    }
  }
  .pluspicker {
    border-bottom: 0;
    .weui-cell__hd {
      width: 155/75rem;
    }
  }
  .bc-t {
    background-color: transparent;
  }
  background-color: #fff;
  font-size: 28/75rem;
  .input {
    padding: 20/75rem 0;
    flex: 1;
    border: none;
    outline: none;
    color: #eb8718;
    -webkit-transform: translate3d(0, 0, 0);
  }

  .rank-score {
    padding: 0 25/75rem;
    .item-title-core {
      display: flex;
      align-items: center;
      width: 150/75rem;
    }
    .score-item {
      height: 100/75rem;
      border-bottom: 1px solid #eee;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;

      .item-check {
        display: flex;
        height: 100%;
        align-items: center;
        padding-left: 30/75rem;
        .check-box {
          height: 45/75rem;
          width: 45/75rem;
          border-radius: 8/75rem;
          border: 1px solid #ddd;
          i {
            &.i-checked::before {
              content: "\EA08";
              display: block;
              color: #ff8600;
              font-size: 26/75rem;
              margin-left: 0.2em;
              margin-right: 0.2em;
            }
          }
        }
      }
      .item-title {
        display: flex;
        align-items: center;
        width: 250/75rem;
      }
    }
    .score-defalut {
      // h-100 flex ai-c jc-b
      height: 100/75rem;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: relative;
    }
  }
  .rank-type {
    height: 90/75rem;
    display: flex;
    align-items: center;
    padding: 0 20/75rem;
    .type-title {
      width: 200/75rem;
    }
    .radio-list {
      display: flex;
      align-items: center;
      margin-right: 20/75rem;
    }
    .radio-item {
      height: 40/75rem;
      border: 1px solid #ccc;
      border-radius: 100%;
      width: 40/75rem;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 10/75rem;
      i {
        &.i-checked::before {
          content: "\EA08";
          display: block;
          color: #ff8600;
          font-size: 26/75rem;
          margin-left: 0.2em;
          margin-right: 0.2em;
        }
      }
    }
  }
  .rank-line {
    background-color: #f2f2f2;
    padding: 20/75rem;
  }
  .item-text {
    flex: 1;
    color: eb8718;
  }
  .item-right {
    content: " ";
    display: inline-block;
    height: 8px;
    width: 8px;
    border-width: 2px 2px 0 0;
    border-color: #c8c8cd;
    border-style: solid;
    -webkit-transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
    transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
    top: -2px;
    position: absolute;
    top: 50%;
    margin-top: -4px;
    right: 2px;
  }
}
</style>
